package com.cf.pay.core.zfb;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.cf.constant.EnumReturnCode;
import com.cf.exception.BizException;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * game-server-ZfbPayService
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/5/17 下午 05:55
 */
public class ZfbPayService {

    /**
     * @param orderId
     * @param money          分
     * @param name
     * @param body
     * @param zfbPayProperty
     * @return
     */
    private static ZfbPayBean zfbPay(String orderId, long money, String name, String body, ZfbPayProperty zfbPayProperty) {
        return zfbPay(orderId, String.valueOf(money / 100D), name, body, zfbPayProperty);
    }

    private static ZfbPayBean zfbPay(String orderId, String money, String name, String body, ZfbPayProperty zfbPayProperty) {
        String out_trade_no = new SimpleDateFormat("yyyymmddmmhhss").format(new Date());//产生一组随机的订单号
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", zfbPayProperty.getAppId(), zfbPayProperty.getPriKey(), "json", "UTF-8", zfbPayProperty.getPubKey(), "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(name);
        model.setSubject(body);
        model.setOutTradeNo(orderId);
        model.setTimeoutExpress("90m");
        model.setTotalAmount(money);
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(zfbPayProperty.getNotifyUrl());//商户外网可以访问的异步地址，不能重定向
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            //就是orderString 可以直接给客户端请求，无需再做处理。
            return new ZfbPayBean(response.getBody());
        } catch (AlipayApiException e) {
            throw new BizException(EnumReturnCode.ERROR.getCode(), "支付宝支付后台异常", e);
        }
    }
}
